﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Web.Routing;

namespace PracticeAzure.Website.Shared
{
    public static class GlobalUtilities
    {
        private static MD5CryptoServiceProvider _md5;
        private static UTF8Encoding _encoding;

        static GlobalUtilities()
        {
            _md5 = new MD5CryptoServiceProvider();
            _encoding = new UTF8Encoding();
        }

        public static string ToBio(this string content)
        {
            // remove the html tags from the content
            content = StripHtml(content);
            if (GlobalConfiguration.BioLength < content.Length)
            {
                return content.Substring(0, GlobalConfiguration.BioLength) + "...";
            }
            else
            {
                return content;
            }
        }

        private static string StripHtml(string source)
        {
            var array = new char[source.Length];
            var arrayIndex = 0;
            var inside = false;
            for (int i = 0; i < source.Length; i++)
            {
                char let = source[i];
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }
                if (!inside)
                {
                    array[arrayIndex] = let;
                    arrayIndex++;
                }
            }
            return new string(array, 0, arrayIndex);
        }

        public static string CalculateMD5(this string content)
        {
            if (string.IsNullOrWhiteSpace(content))
            {
                return string.Empty;
            }
            else
            {
                var buffer = _md5.ComputeHash(_encoding.GetBytes(content.Trim().ToLower()));
                var builder = new StringBuilder(buffer.Length * 2);
                for (var i = 0; i < buffer.Length; i++)
                {
                    builder.Append(buffer[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }

        //public static string GetAttachmentURL(string fileName)
        //{
        //    var account = Microsoft.WindowsAzure.CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        //    var container = GlobalConfiguration.AttachementContainerName;
        //    return string.Format("{0}/{1}/{2}", account.BlobEndpoint.AbsoluteUri, container, fileName);
        //}

        public static SqlParameter AddReturnValue(this SqlParameterCollection parameters)
        {
            var parameter = new SqlParameter("@RETURN_VALUE", 0) { Direction = ParameterDirection.ReturnValue };
            parameters.Add(parameter);
            return parameter;
        }

        public static object GetReturnValue(this SqlCommand cmd)
        {
            object result = null;
            try
            {
                var parameter = cmd.Parameters["@RETURN_VALUE"];
                result =  parameter.Value;
            }
            catch { /* ingore the error just return the default value back */ }
            return result;
        }

        public static RouteValueDictionary Clone(this RouteValueDictionary values, params KeyValuePair<string, string>[] routeValues)
        {
            var output = new RouteValueDictionary();
            // copy the source route data
            foreach (var value in values)
            {
                output.Add(value.Key, value.Value);
            }
            // add more route data if needed
            if (routeValues != null && routeValues.Any())
            {
                foreach (var addValue in routeValues)
                {
                    output.Add(addValue.Key, addValue.Value);
                }
            }
            return output;
        }
    }
}